var dbmodel = require('../dbmodel/dbmodel.js');
var fans = dbmodel.model('fans');
var attention = dbmodel.model('attention');

// 关注
exports.attention = function(req, res) {
	let attentionData = {
		userID: req.body.userID,
		attentionID: req.body.attentionID,
		createTime: new Date()
	}
	let fansData = {
		userID: req.body.attentionID,
		fansID: req.body.userID,
		createTime: new Date()
	}
	let Attention = new attention(attentionData)
	let Fans = new fans(fansData)

	Attention.save(function(err, result) {
		if (err) {
			res.send(err);
		} else {
			Fans.save(function(err, result) {
				if (err) {
					res.send(err);
				} else {
					res.send({
						status: 200,
						info: '关注成功'
					});
				}
			})
		}
	})
}

// 是否关注
exports.isAttention = function(req, res) {
	let wherestr = {
		'userID': req.body.userID,
		'attentionID': req.body.attentionID
	};
	let out = {
		'userID': 1,
		'attentionID': 1,
		'createTime': 1
	};
	attention.findOne(wherestr, out, function(err, result) {
		if (err) {
			res.send({
				status: 500
			});
		} else {
			res.send({
				status: 200,
				result
			});
		}
	})
}

// 关注表
exports.showAttention = function(req, res) {
	let wherestr = {
		'userID': req.body.userID
	};
	let query = attention.find(wherestr);
	query.populate('userID');
	query.populate('attentionID');
	// 排序方式 time 倒序
	query.sort({
		'createTime': -1
	});
	// 查询结果
	query.exec().then(function(e) {
		res.send({
			status: 200,
			info: e
		});
	}).catch(function(err) {
		res.send({
			status: 500,
			err
		})
	})
}

// 粉丝表
exports.showFans = function(req, res) {
	let wherestr = {
		'userID': req.body.userID
	};
	
	let query = fans.find(wherestr);
	query.populate('userID');
	query.populate('fansID');
	// 排序方式 time 倒序
	query.sort({
		'createTime': -1
	});
	// 查询结果
	query.exec().then(function(e) {
		res.send({
			status: 200,
			info: e
		});
	}).catch(function(err) {
		res.send({
			status: 500,
			err
		})
	})
}

// 取消关注
exports.deleteAttention = function(req, res) {
	let attentionData = {
		'userID': req.body.userID,
		'attentionID': req.body.attentionID
	};
	let fansData = {
		'userID': req.body.attentionID,
		'fansID': req.body.userID
	};

	attention.deleteOne(attentionData, function(err, result) {
		if (err) {
			res.send({
				status: 500,
				info: '取关失败'
			});
		} else {
			fans.deleteOne(fansData, function(err, result) {
				if (err) {
					res.send({
						status: 500,
						info: '取关失败'
					});
				} else {
					res.send({
						status: 200,
						info: '取关成功'
					});
				}
			})
		}
	})
}

